

from info import redis_store
from info.models import User, News, Category
from info.utils.response_code import RET
from . import index_bule
from flask import render_template,current_app, session, jsonify,request

#加载首页的新闻
@index_bule.route('/newslist')
def newslist():
    #获取参数
    #新闻类型
    cid = request.args.get('cid','1')#如果不会不到,使用后面的参数
    #当前页数
    page = request.args.get('page','1')
    #每页多少条
    per_page = request.args.get('per_page','10')

    #参数类型转化,为了paginte准备
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        page = 1
        per_page =10

    #分页查询
    try:
        #判断分类编号是否不等于1,罪行分类是按时间排序
        filters = []
        if cid != '1':
            filters.append(News.category_id==cid)


        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='分页失败')

    #获取分页对象想的属性  总页数   当前页  当前项
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items


    #将当夜对象列表转换成字典列表
    newsList = []

    for item in  items:
        newsList.append(item.to_dict())

    #响应
    return  jsonify(errno=RET.OK,errmsg='捕获成功',totalPage=totalPage,currentPage = currentPage,newsList=newsList)

#index模板启动
@index_bule.route('/')
def hello_world():
    #进入网页是判断用户是否登陆
    #获取session参数
    user_id = session.get('user_id')
    #判断用户是否存在
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)


    #热门排行排行
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(10).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询错误')

    #将新闻遍历出来转换为字典
    click_news_list = []
    for news in news_list:
        click_news_list.append(news.to_dict())

    #将分类信息带到首页
    try:
        categories = Category.query.all()

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询错误')

    category_list = []
    for category in categories:
        category_list.append(category.to_dict())



    #将用户的信息转化成字典
    dict_data = {
        #判断下用户是否存在
        'user_info':user.to_dict()  if user else "",
        'click_news_list':click_news_list,
        'category_list':category_list
    }
    return render_template('news/index.html',data=dict_data)

#新闻logo设置 /favicon.ico
@index_bule.route('/favicon.ico')
def web_logo():

    return current_app.send_static_file('news/favicon.ico')